import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { File } from 'ionic-native';
import { GLBookContent } from './GLBookContent';
import { GLFolderLike } from './GLFolderLike';
import { GLFolder } from './GLFolder';
import { Platform } from 'ionic-angular';

declare var cordova;

export let PROXY = true;

export abstract class GLAPI {

    private catalogPromise: Promise<GLFolder>;

    get fs() {
      return cordova.file.externalDataDirectory;
    }

    constructor(private platform: Platform) {

    }

    protected ready() {
      return this.platform.ready();
    }

    abstract isBookAvailable(id: string): Promise<boolean>;

    abstract getBook(id: string, url: string, parentFolder: GLFolderLike): Promise<GLBookContent>;

    abstract loadCatalog(): Promise<GLFolder>;

    getCatalog() {
      if(!this.catalogPromise) {
        this.catalogPromise = this.loadCatalog();
      }
      return this.catalogPromise;
    }

    protected query(params) {
        var tr = "";
        for (var key in params) {
            if (tr.length > 0) {
                tr += "&";
            }
            else {
                tr += "?";
            }
            tr += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
        }
        return tr;
    }
}
